package com.teradata.olingo.processor;

import javax.servlet.AsyncContext;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/5/7 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */
public class AsyncRequestProcessor implements Runnable {

    private AsyncContext asyncContext;
    private int secs;

    public AsyncRequestProcessor() {
    }

    public AsyncRequestProcessor(AsyncContext asyncCtx, int secs) {
        this.asyncContext = asyncCtx;
        this.secs = secs;
    }

    @Override
    public void run() {
        System.out.println("Async Supported? " + Thread.currentThread().getName()
                + asyncContext.getRequest().isAsyncSupported());
        longProcessing(secs);
        try {
                System.out.println("Async Start:" + Thread.currentThread().getName());
            String data = "中国";
            //byte[] dataByteArr = data.getBytes("UTF-8");//将字符转换成字节数组，指定以UTF-8编码进行转换
            HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
            response.setHeader("content-type", "text/html;charset=UTF-8");
            PrintWriter out = asyncContext.getResponse().getWriter();
            out.write(data);
            System.out.println("Async End:" + Thread.currentThread().getName());
        } catch (IOException e) {
            e.printStackTrace();
            asyncContext.complete();
        } catch (IllegalStateException ie) {
            //asyncContext.complete();
            System.out.println("IllegalStateException:" + ie.getMessage());
        } finally {
            try {
                asyncContext.complete();
            } catch (Exception e) {
                System.out.println(e.getClass().getName() + " msg:" + e.getMessage());
            }
        }
        //complete the processing

    }

    private void longProcessing(int secs) {
        // wait for given time before finishing
        try {
            Thread.sleep(secs);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}